package com.mjk.manager.monitor.logger.work;

import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.base.work.BaseWork;
import com.mjk.common.base.work.annotation.BeeWork;
import jakarta.websocket.Session;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 监控日志获取
 */
@BeeWork(work = "monitorlog")
public class MonitorLoggerWork extends BaseWork {
    private static Map<String, Integer> lengthMap = new ConcurrentHashMap<String, Integer>();

    public BeeResponse getLogger(String id) {
        return null;
    }

    private String getTest(String filePath, Session session) throws Exception {
        //日志文件路径，获取最新的
        boolean first = true;
        //字符流
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath));) {
            Object[] lines = reader.lines().toArray();

            //只取从上次之后产生的日志
            Object[] copyOfRange = Arrays.copyOfRange(lines, lengthMap.get(session.getId()), lines.length);

            //对日志进行着色，更加美观  PS：注意，这里要根据日志生成规则来操作
            for (int i = 0; i < copyOfRange.length; i++) {
                String line = (String) copyOfRange[i];
                //先转义
                line = line.replace("&", "&amp;")
                        .replace("<", "&lt;")
                        .replace(">", "&gt;")
                        .replace("\"", "&quot;");

                //处理等级
                line = line.replace("DEBUG", "<span style='color: blue;'>DEBUG</span>");
                line = line.replace("INFO", "<span style='color: green;'>INFO</span>");
                line = line.replace("WARN", "<span style='color: orange;'>WARN</span>");
                line = line.replace("ERROR", "<span style='color: red;'>ERROR</span>");

                //处理类名
                String[] split = line.split("]");
                if (split.length >= 2) {
                    String[] split1 = split[1].split("-");
                    if (split1.length >= 2) {
                        line = split[0] + "]" + "<span style='color: #298a8a;'>" + split1[0] + "</span>" + "-" + split1[1];
                    }
                }
                copyOfRange[i] = line;
            }

            //存储最新一行开始
            lengthMap.put(session.getId(), lines.length);
            //第一次如果太大，截取最新的200行就够了，避免传输的数据太大
            if (first && copyOfRange.length > 200) {
                copyOfRange = Arrays.copyOfRange(copyOfRange, copyOfRange.length - 200, copyOfRange.length);
                first = false;
            }
            String result = StringUtils.join(copyOfRange, "<br/>");
            return result;
        } catch (Exception e) {
            return null;
        }
    }
}
